

from pydub import AudioSegment
import os
# 把ogg转到wav格式
def fromOgg2Wav(src,dst=''):
    if not dst:
        #Split the pathname path into a pair (root, ext) such that root + ext == path, and the extension,
        # ext, is empty or begins with a period and contains at most one period.
        dst = os.path.splitext(src)[0]+'.wav'

    # convert mp3 to wav
    sound = AudioSegment.from_ogg(src)
    sound.export(dst, format="wav")



import speech_recognition as sr
from os import path





# 语音转文字
def voice2Text(file_name):
    content = ''
    voice_file = file_name
    if not os.path.exists(voice_file):
        return 'ERROR：文件不存在'
    # use the audio file as the audio source
    r = sr.Recognizer()
    with sr.AudioFile(voice_file) as source:
        audio = r.record(source)
    try:
        content = r.recognize_google(audio,language='zh-CN')
        print("Google Speech Recognition:" + content)
    except sr.UnknownValueError:
        print("Google Speech Recognition could not understand audio")
    except sr.RequestError as e:
        print("Google Speech Recognition error; {0}".format(e))

    return content or 'ERROR：转文本失败'
